import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { HttpExceptionFilter } from 'src/common/filters/http-exception.filter';
import { AllExceptionsFilter } from 'src/common/filters/exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalFilters(new AllExceptionsFilter(app.get(HttpAdapterHost)));

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 自动转换对象为 DTO 类实例
      whitelist: true, // 自动剔除 DTO 中未定义的属性
    }),
  );

  // swagger 配置
  const documentOptions = new DocumentBuilder()
    .setTitle('律录API接口文档')
    .setDescription('律录API接口文档')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, documentOptions);
  SwaggerModule.setup('swagger-ui', app, document);

  const configService = app.get(ConfigService);
  const port = configService.get('server.port') || 3000;
  await app.listen(port);
  console.log('启动成功，监听运行端口：' + `localhost:${port}`);
}
bootstrap();
